import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import { get, set } from 'lodash';
import {
  Checkbox,
  KeyValue,
  Row,
  Col,
  Button,
  Modal,
  MultiColumnList,
  SearchField,
  AccordionSet, Accordion, Label
} from '@folio/stripes/components';
import { stripesConnect } from '@folio/stripes/core';
import {
  StripesConnectedSource
} from '@folio/stripes/smart-components';
import { attendanceState } from './enum';
import css from './style.css';

class SupplementForm extends React.Component {
  static manifest = Object.freeze({
    queryParam:{ initialValue: '' },

    resultCount: { initialValue: 5 },
    userResultCount: { initialValue: 5 },
    totalCount:{ initialValue:0 },
    userQueryParam:{ initialValue:'' },
    AttendSearchRecordsRecords: {
      type: 'okapi',
      path: 'party/attend',
    },
    userQuery: {
      type:'okapi',
      path: 'party/users',
      accumulate: true,
      records: 'users',
      recordsRequired: '%{userResultCount}',
      perRequest:5,
      limitParam:'size',
      GET: {
        params: {
          // eslint-disable-next-line no-template-curly-in-string
          query: '${userQueryParam}'
        }
      }
    },
    GetPartyActivityList: {
      type: 'okapi',
      accumulate: true,
      path: 'party/info',
      records: 'partyGroup',
      perRequest: 5,
      limitParam: 'size',
      GET: {
        params: {
          // eslint-disable-next-line no-template-curly-in-string
          query: '(isDel = 0 ${queryParam}  and isCalendar = 0 )'
        }
      }
    },
  })

  static propTypes = {
    handleCancel: PropTypes.func.isRequired,
    reset: PropTypes.func,
    stripes:PropTypes.object,
    mutator:PropTypes.object,
    resources:PropTypes.object,
    operator:PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      barcode:'',
      value: '',
      loading: false,
      barcodeLoading:false,
      partyData:'',
      readerData:'',
      status:  {
        unarrived:false,
        arrived:true,
        lateed:false,
        leave:false,
        early:false,
        unsigned:false
      }
    };
    this.clearValue = this.clearValue.bind(this);
    this.changeValue = this.changeValue.bind(this);
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger, 'AttendSearchRecordsRecords');
    this.source = new StripesConnectedSource(this.props, this.logger, 'GetPartyActivityList');
  }

  activityFilter = () => {
    if (this.state.value) {
      const tmp = ` and partyName == *${this.state.value}* `;
      this.props.mutator.queryParam.replace(tmp);
      this.props.mutator.GetPartyActivityList.GET();
    }
  }

  userFilter=() => {
    if (this.state.barcode) {
      const tmp = `${this.state.barcode}`;
      this.props.mutator.userQueryParam.replace(tmp);
      this.props.mutator.userQuery.GET();
    }
  }

  reset = () => {
    this.props.reset();
  }

  clearValue() {
    this.setState({
      value: '',
    });
  }

  changeValue(e) {
    clearInterval(this.asyncFaker);

    this.setState({
      value: e.target.value,
      loading: true,
    });

    this.asyncFaker = setInterval(() => {
      this.setState({
        loading: false,
      });
    }, 250);
  }

  clearBarcodeValue=() => {
    this.setState({
      barcode: '',
    });
  }

  changeBarcodeValue=(e) => {
    clearInterval(this.asyncFaker);

    this.setState({
      barcode: e.target.value,
      barcodeLoading: true,
    });

    this.asyncFaker = setInterval(() => {
      this.setState({
        barcodeLoading: false,
      });
    }, 250);
  }

  changeStatus=(key) => {
    this.setState((preState) => {
      const status = preState.status;
      Object.keys(status).forEach((str) => {
        if (str === key) {
          status[str] = true;
        } else {
          status[str] = false;
        }
      });
      return {
        status
      };
    });
  }

  commitValue=() => {
    const user = this.state.readerData;
    const partyData = this.state.partyData;
    const status = this.state.status;
    let attendState = 1;
    const { mutator, handleCancel } = this.props;
    Object.keys(status).forEach((key) => {
      if (status[key]) {
        const target = attendanceState.find(item => item.name === key);
        attendState = target.id;
      }
    });
    const params = {
      readId: user.barcode,
      readerReserveGroup:
              [
                {
                  name:user.username,
                  barcode:user.barcode,
                  mobilePhone: user.personal.mobilePhone
                }
              ],
      propertyName:partyData.propertyName,
      partyId: partyData.id,
      partyName: partyData.partyName,
      partyStartDate:partyData.partyStartDate,
      state: 1,
      attendState,
      isDel:0,
      operator:this.props.operator
    };
    delete params.operator.addresses;
    delete params.operator.preferredContactTypeId;
    delete params.operator.servicePoints;
    delete params.operator.curServicePoint;
    delete params.operator.dateOfBirth;
    mutator.AttendSearchRecordsRecords.POST(params).then((response) => {
      handleCancel(false);
    }).catch((e) => {
      console.log(e);
    });
  }

  render() {
    const { handleCancel,intl } = this.props;
    const resultsFormatter = {
      name: item => `${(item || {}).partyName}`,
      operation: (item) => {
        return (
          <Button onClick={() => {
            this.setState({
              partyData:item
            });
          }}
          >
            <FormattedMessage id="ui-party.select" />
          </Button>
        );
      }
    };
    const userFormatter = {
      name: item => `${(item || {}).partyName}`,
      'personal.mobilePhone': item => `${(item.personal || {}).mobilePhone || '未设置'}`,
      operation: (item) => {
        return (
          <Button onClick={() => {
            this.setState({
              readerData:item
            });
          }}
          >
            <FormattedMessage id="ui-party.select" />
          </Button>
        );
      }
    };
    const {
      resources,

    } = this.props;

    const PartyActivityList = get(resources, 'GetPartyActivityList.records', []);
    const totalCount = get(resources, 'GetPartyActivityList.other.totalRecords', 0);
    const PartyUserList = get(resources, 'userQuery.records', []);
    const userTotalCount = get(resources, 'userQuery.other.totalRecords', 0);
    let saveFlag = true;

    if ((!!this.state.partyData && !!this.state.readerData)) {
      saveFlag = false;
    }
    return (

      <Modal
        onClose={() => {
          this.props.mutator.queryParam.replace('');
          this.props.mutator.userQueryParam.replace('');
          // set(resources, 'userQuery.records', []);
          handleCancel(false);
        }}
        dismissible
        closeOnBackgroundClick
        open
        label={<FormattedMessage id={"ui-party.other.supplementary.attendance.check-in"}/>}
      >
        <AccordionSet>
          <Accordion label={<FormattedMessage id={"ui-party.other.activity.query"}/>} id="ex-1">
            <Row className={css.formClass}>
              <Col xs={10}>
                <SearchField
                  onClear={this.clearValue}
                  value={this.state.value}
                  loading={this.state.loading}
                  onChange={(e) => { this.changeValue(e); }}
                  placeholder={intl.formatMessage({id:"ui-party.other.please.enter.the.event.name.to.search"})}
                  aria-label="Search for stuff."
                  clearSearchId="clear-search-button"
                  id="clear-sesrch-field"
                />
              </Col>
              <Col xs={2}>
                <Button onClick={() => { this.activityFilter(); }}><FormattedMessage id="ui-party.search" /></Button>
              </Col>
            </Row>
            <MultiColumnList
              isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />}
              contentData={PartyActivityList}
              onNeedMoreData={() => { this.source.fetchMore(5); }}
              totalCount={totalCount}
              formatter={resultsFormatter}
              maxHeight={200}
              virtualize
              interactive={false}
              visibleColumns={['partyName', 'partyStartDate', 'venue', 'operation']}
              columnMapping={{
                partyName: <FormattedMessage id="ui-party.loans.columns.party.partyName" />,
                propertyName: (
                  <FormattedMessage id="ui-party.loans.columns.party.propertyName" />
                ),
                venue: (
                  <FormattedMessage id="ui-party.loans.columns.party.venue" />
                ),
                partyStartDate: (
                  <FormattedMessage id="ui-party.loans.columns.party.partyDate" />
                ),
                operation: <FormattedMessage id="ui-party.loans.columns.operating" />,
              }}
            />
          </Accordion>
          <Accordion label={<FormattedMessage id={"ui-party.other.reader.query"}/>} id="ex-2">

            <Row className={css.formClass}>
              <Col xs={10}>
                <SearchField
                  onClear={this.clearBarcodeValue}
                  value={this.state.barcode}
                  loading={this.state.barcodeLoading}
                  onChange={(e) => { this.changeBarcodeValue(e); }}
                  placeholder={intl.formatMessage({id:"ui-party.other.please.enter.the.reader.id.number.to.search"})}
                  aria-label="Search for stuff."
                  clearSearchId="clear-search-button"
                  id="clear-sesrch-field"
                />
              </Col>
              <Col xs={2}>
                <Button onClick={() => { this.userFilter(); }}><FormattedMessage id="ui-party.search" /></Button>
              </Col>
            </Row>
            <MultiColumnList
              isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />}
              contentData={PartyUserList}
              onNeedMoreData={() => { this.source.fetchMore(5); }}
              totalCount={userTotalCount}
              formatter={userFormatter}
              maxHeight={200}
              virtualize
              interactive={false}
              visibleColumns={['username', 'barcode', 'personal.mobilePhone', 'operation']}
              columnMapping={{
                username: <FormattedMessage id="ui-party.loans.columns.readerName" />,
                barcode: (
                  <FormattedMessage id="ui-party.loans.columns.readerAccount" />
                ),
                'personal.mobilePhone': (
                  <FormattedMessage id="ui-party.attend.personal.mobilePhone" />
                ),

                operation: <FormattedMessage id="ui-party.loans.columns.operating" />,
              }}
            />
          </Accordion>
          <Accordion label={<FormattedMessage id={"ui-party.other.supplementary.attendance"}/>} id="ex-3">
            <Row>
              <Col xs={4}>
                <KeyValue
                  label={<Label required><FormattedMessage id="ui-party.loans.columns.party.partyName" /></Label>}
                  value={(this.state.partyData || {}).partyName || intl.formatMessage({id:"ui-party.other.unselected"})}
                />
              </Col>
              <Col xs={4}>
                <KeyValue
                  label={<Label required><FormattedMessage id="ui-party.loans.columns.readerName" /></Label>}
                  value={(this.state.readerData || {}).username || intl.formatMessage({id:"ui-party.other.unselected"})}

                />
              </Col>
              <Col xs={4}>
                <KeyValue
                  label={<Label required><FormattedMessage id="ui-party.loans.columns.readerAccount" /></Label>}
                  value={(this.state.readerData || {}).barcode || intl.formatMessage({id:"ui-party.other.unselected"})}
                />
              </Col>
            </Row>
            <Label required><FormattedMessage id="ui-party.loans.columns.attend.status" /></Label>
            <Row style={{ marginBottom:30 }}>

              <Col xs={2}>

                <Checkbox
                  label={<FormattedMessage id="ui-party.loans.columns.unarrived" />}
                  checked={this.state.status.unarrived}
                  inline
                  onChange={() => {
                    this.changeStatus('unarrived');
                  }}
                />
              </Col>
              <Col xs={2}>
                <Checkbox
                  label={<FormattedMessage id="ui-party.loans.columns.arrived" />}

                  inline
                  checked={this.state.status.arrived}
                  onChange={() => {
                    this.changeStatus('arrived');
                  }}
                />
              </Col>
              <Col xs={2}>
                <Checkbox
                  label={<FormattedMessage id="ui-party.loans.columns.lateed" />}
                  checked={this.state.status.lateed}
                  inline
                  onChange={() => {
                    this.changeStatus('lateed');
                  }}
                />
              </Col>
              <Col xs={2}>
                <Checkbox
                  label={<FormattedMessage id="ui-party.loans.columns.leave" />}
                  checked={this.state.status.leave}
                  inline
                  onChange={() => {
                    this.changeStatus('leave');
                  }}
                />
              </Col>
              <Col xs={2}>
                <Checkbox
                  label={<FormattedMessage id="ui-party.loans.columns.leave.early" />}
                  checkedvalue={this.state.status.early}
                  inline
                  onChange={() => {
                    this.changeStatus('early');
                  }}
                />
              </Col>
              <Col xs={2}>
                <Checkbox
                  label={<FormattedMessage id="ui-party.loans.columns.unsigned" />}
                  checked={this.state.status.unsigned}
                  inline
                  onChange={() => {
                    this.changeStatus('unsigned');
                  }}
                />
              </Col>
            </Row>
            <Row center="xs">
              <Col xs={12}>
                <Button
                  disabled={saveFlag}
                  onClick={() => {
                    this.commitValue();
                  }}
                >
                  <FormattedMessage id="ui-party.saveAndExit" />

                </Button>
              </Col>
            </Row>
          </Accordion>
        </AccordionSet>

      </Modal>

    );
  }
}
export default injectIntl(stripesConnect(SupplementForm));
